package com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.impl.salesorder;

import com.alibaba.citrus.cr.common.enums.ordercenter.DictionaryTypeEnum;
import com.alibaba.citrus.cr.common.enums.ordercenter.OrderCategoryEnum;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.*;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemGroupAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ShipToPartyByAccurateQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.SoldToPartyByAccurateQueryRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.*;
import com.alibaba.citrus.cr.mn.order.center.facade.function.assemble.OrderBizAssemble;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.crpricecenter.api.creditquery.dto.BatchQueryCreditListRequest;
import com.epoch.app.crpricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.crpricecenter.model.dto.CreditInfoSDO;
import com.epoch.app.crpricecenter.model.dto.CreditQueryRequest;
import com.epoch.app.mnordercenter.model.dto.*;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomCreateRequest;
import com.epoch.app.mnordercenter.sdo.SapCreditSDO;
import com.epoch.app.mnordercenter.service.MnOrderCenterService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName OrderBizAssembleOfMember
 * @description: TODO
 * @date 2023/05/17 09:49
 * @version: 1.0
 */
@Service
@Order(5)
public class SalesOrderCreateBizAssembleOfCustomerCenter implements OrderBizAssemble<SalesOrderBizCreateRequest> {
    private static final Log log = Log.getLogger(SalesOrderCreateBizAssembleOfCustomerCenter.class);

    //业务渠道状态，已禁用："0" ,已启用："1"
    private static final String BUSINESS_CHANNEL_STATUS_DISABLED = "0";
    private static final String SALES_ORGANIZATION_CODE = "20";
    private static final String SAP_ORG_CODE = "sapOrgCode";

    @Resource
    private SoldToPartyAbilityAdapter soldToPartyAbilityAdapter;
    @Resource
    private ShipToPartyAbilityAdapter shipToPartyAbilityAdapter;
    @Resource
    private BusinessChannelAbilityAdapter businessChannelAbilityAdapter;
    @Resource
    private CreditQueryService creditQueryService;
    @Resource
    private CustomerCenterAdapter customerCenterAdapter;
    @Resource
    private MnOrderCenterService mnOrderCenterService;
    @Resource
    private BaseDataServiceAdapter baseDataServiceAdapter;
    @Resource
    private ItemQueryAdapter itemQueryAdapter;
    @Resource
    private CargoZoneAdapter cargoZoneAdapter;

    @Override
    public Map<String, Object> query(SalesOrderBizCreateRequest bizCreateRequest) {
        return query(Lists.newArrayList(bizCreateRequest));
    }

    @Override
    public Map<String, Object> query(List<SalesOrderBizCreateRequest> bizCreateRequests) {
        log.info("SalesOrderCreateBizAssembleOfCustomerCenter#query bizCreateRequests={}", JSON.toJSONString(bizCreateRequests));
        try {
            // 产品组
            Map<String, ItemGroupAbilityDTO> scItemGroupMap = queryScItemGroupMap(bizCreateRequests);
            // 客户送达方
            Map<String, ShipToPartyByAccurateQueryDTO> shipToPartyMap = queryShipToPartyByAccurate(bizCreateRequests, scItemGroupMap);
            // 客户售达方
            Map<String, SoldToPartyByAccurateQueryDTO> soldToPartyMap = querySoldToPartyByAccurate(bizCreateRequests, scItemGroupMap);
            // 业务单元
            Map<String, DictionaryResponse> businessUnitMap = queryBusinessUnit();
            // 销售组织
            Map<String, String> salesOrgMap = querySalesOrgByCodeListV2(bizCreateRequests);
            // 销售部门
            Map<String, String> salesDeptMap = querySalesDeptByCodeList(bizCreateRequests);
            // 销售渠道
            Map<String, String> salesChannelMap = querySalesChannelByCodeList(bizCreateRequests);
            // 业务渠道
            Map<String, BusinessChannelDTO> bizChannelMap = queryBizChannelByCodeList(bizCreateRequests);
            // 信贷数据
            Map<String, Long> creditMap = batchQueryCreditList(bizCreateRequests);
            // 成本中心
            Map<String, String> costCenterNameMap = queryCostCenterByCodeList(bizCreateRequests);

            Map<String, Object> result = Maps.newHashMap();
            result.put(SC_ITEM_GROUP, scItemGroupMap);
            result.put(SHIP_TO_PARTY, shipToPartyMap);
            result.put(SOLD_TO_PARTY, soldToPartyMap);
            result.put(BUSINESS_UNIT_CODE, businessUnitMap);
            result.put(SALES_ORGANIZATION, salesOrgMap);
            result.put(SALES_DEPARTMENT, salesDeptMap);
            result.put(SALES_CHANNEL, salesChannelMap);
            result.put(BUSINESS_CHANNEL, bizChannelMap);
            result.put(CREDIT_INFO, creditMap);
            result.put(COST_CENTER, costCenterNameMap);

            log.info("SalesOrderCreateBizAssembleOfCustomerCenter#query result={}", JSONObject.toJSONString(result));
            return result;
        } catch (Exception e) {
            log.error("SalesOrderCreateBizAssembleOfCustomerCenter#query error", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public Result<String> assemble(Map<String, Object> queryResponseMap, SalesOrderBizCreateRequest bizCreateRequest) {
        log.info("SalesOrderCreateBizAssembleOfCustomerCenter#assemble queryResponseMap={} bizCreateRequest={}",
                JSON.toJSONString(queryResponseMap), JSON.toJSONString(bizCreateRequest));
        // 产品组
        Map<String, ItemGroupAbilityDTO> scItemGroupMap = getBizInfoMap(queryResponseMap, SC_ITEM_GROUP, ItemGroupAbilityDTO.class);
        // 客户送达方
        Map<String, ShipToPartyByAccurateQueryDTO> shipToPartyMap = getBizInfoMap(queryResponseMap, SHIP_TO_PARTY, ShipToPartyByAccurateQueryDTO.class);
        // 客户售达方
        Map<String, SoldToPartyByAccurateQueryDTO> soldToPartyMap = getBizInfoMap(queryResponseMap, SOLD_TO_PARTY, SoldToPartyByAccurateQueryDTO.class);
        // 业务单元
        Map<String, DictionaryResponse> businessUnitMap = getBizInfoMap(queryResponseMap, BUSINESS_UNIT_CODE, DictionaryResponse.class);
        // 销售组织
        Map<String, String> salesOrgMap = getBizInfoMap(queryResponseMap, SALES_ORGANIZATION, String.class);
        // 销售部门
        Map<String, String> salesDeptMap = getBizInfoMap(queryResponseMap, SALES_DEPARTMENT, String.class);
        // 销售渠道
        Map<String, String> salesChannelMap = getBizInfoMap(queryResponseMap, SALES_CHANNEL, String.class);
        // 业务渠道
        Map<String, BusinessChannelDTO> bizChannelMap = getBizInfoMap(queryResponseMap, BUSINESS_CHANNEL, BusinessChannelDTO.class);
        // 信贷数据
        Map<String, Long> creditMap = getBizInfoMap(queryResponseMap, CREDIT_INFO, Long.class);
        // 成本中心
        Map<String, String> costCenterNameMap = getBizInfoMap(queryResponseMap, COST_CENTER, String.class);

        // 产品组
        ItemGroupAbilityDTO scItemGroup = scItemGroupMap.get(bizCreateRequest.getProductGroupCode());
        if (Objects.isNull(scItemGroup)) {
            return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-036", "产品组编码/名称不存在");
        }
        bizCreateRequest.setProductGroupName(scItemGroup.getProductGroupName());

        // 业务单元
        DictionaryResponse businessUnit = businessUnitMap.get(bizCreateRequest.getBusinessUnitCode());
        if (Objects.isNull(businessUnit)) {
            return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-011", "业务单元编码不存在");
        }
        bizCreateRequest.setBusinessUnitName(businessUnit.getName());

        // 销售组织
//        String salesOrgKey = SalesOrgTypeEnum.SALES_ORG.getCode() + "_" + bizCreateRequest.getSalesOrganizationCode();
//        if (OrderCategoryEnum.GROUP.getCode().equals(bizCreateRequest.getOrderCategoryCode())) {
//            salesOrgKey = bizCreateRequest.getSalesOrganizationCode();
//        }
        String salesOrganizationName = salesOrgMap.get(bizCreateRequest.getSalesOrganizationCode());
        if (StringUtils.isBlank(salesOrganizationName)) {
            return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-034", "销售组织编码/名称不存在");
        }
        bizCreateRequest.setSalesOrganizationName(salesOrganizationName);

        // 业务渠道
        BusinessChannelDTO businessChannelDTO = bizChannelMap.get(bizCreateRequest.getBusinessChannel());
        if (Objects.isNull(businessChannelDTO) || BUSINESS_CHANNEL_STATUS_DISABLED.equals(businessChannelDTO.getStatus())) {
            return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-051", "业务渠道不存在");
        }
        bizCreateRequest.setBusinessChannelName(businessChannelDTO.getChannelName());

        // 客户售达方
        SoldToPartyByAccurateQueryDTO soldToParty = soldToPartyMap.get(bizCreateRequest.getCustomerCode());
        if (Objects.isNull(soldToParty)) {
            return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-032", "售达方编码/名称不存在");
        }
        bizCreateRequest.setCustomerName(soldToParty.getSoldToPartyName());
        // 集团售达方
        if (StringUtils.isNotBlank(bizCreateRequest.getGroupCustomerCode())) {
            SoldToPartyByAccurateQueryDTO groupSoldToParty = soldToPartyMap.get(bizCreateRequest.getGroupCustomerCode());
            if (Objects.isNull(groupSoldToParty)) {
                return Result.fail(bizCreateRequest.getGroupCustomerCode(), "OC-01-001-01-16-032", "集团售达方编码/名称不存在");
            }
        }

        // 客户送达方
        ShipToPartyByAccurateQueryDTO shipToParty = shipToPartyMap.get(bizCreateRequest.getShipToPartyCode());
        if (Objects.isNull(shipToParty)) {
            return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-033", "送达方编码/名称不存在");
        }
        bizCreateRequest.setShipToPartyName(shipToParty.getShipToPartyName());
        // 集团送达方
        if (StringUtils.isNotBlank(bizCreateRequest.getGroupShipToPartyCode())) {
            ShipToPartyByAccurateQueryDTO groupShipToParty = shipToPartyMap.get(bizCreateRequest.getGroupShipToPartyCode());
            if (Objects.isNull(groupShipToParty)) {
                return Result.fail(bizCreateRequest.getGroupShipToPartyCode(), "OC-01-001-01-16-033", "集团送达方编码/名称不存在");
            }
        }
        if (OrderCategoryEnum.GROUP.getCode().equals(bizCreateRequest.getOrderCategoryCode())) {
            // 集团销售订单，若未传入，根据【产品组+业务渠道+销售组织+售达方+送达方】查询客户中心送达方档案，获取销售部门编码、名称、销售组编码、名称后保存
            if (StringUtils.isBlank(bizCreateRequest.getSalesChannelCode())) {
                bizCreateRequest.setSalesChannelCode(shipToParty.getOuterSalesDepartmentCode()); // 销售办公室
            }
            if (StringUtils.isBlank(bizCreateRequest.getSalesChannelName())) {
                bizCreateRequest.setSalesChannelName(shipToParty.getOuterSalesDepartment());
            }
            if (StringUtils.isBlank(bizCreateRequest.getSalesDepartmentCode())) {
                bizCreateRequest.setSalesDepartmentCode(shipToParty.getOuterSalesGroupCode()); // 销售组
            }
            if (StringUtils.isBlank(bizCreateRequest.getSalesDepartmentName())) {
                bizCreateRequest.setSalesDepartmentName(shipToParty.getOuterSalesGroup());
            }
        } else if (OrderCategoryEnum.STOCK.getCode().equals(bizCreateRequest.getOrderCategoryCode())) {
            // 一盘货销售订单
            // 若传入，中台无校验，以传入的为准
            // 若未传入，则留空
        } else {
            // 分子公司销售订单
            if (StringUtils.isNotBlank(bizCreateRequest.getSalesDepartmentCode())) {
                String salesDepartmentName = salesDeptMap.get(bizCreateRequest.getSalesDepartmentCode());
                if (StringUtils.isBlank(salesDepartmentName)) {
                    return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-035", "销售部门编码/名称不存在");
                }
                bizCreateRequest.setSalesDepartmentName(salesDepartmentName);
            }
            if (StringUtils.isNotBlank(bizCreateRequest.getSalesChannelCode())) {
                String salesChannelName = salesChannelMap.get(bizCreateRequest.getSalesChannelCode());
                if (StringUtils.isBlank(salesChannelName)) {
                    return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-037", "销售渠道编码/名称不存在");
                }
                bizCreateRequest.setSalesChannelName(salesChannelName);
            }
        }

        // 成本中心
        if (!StringUtils.isBlank(bizCreateRequest.getCostCenterCode()) && !costCenterNameMap.containsKey(bizCreateRequest.getCostCenterCode())) {
            return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-029", "成本中心不存在");
        }
        bizCreateRequest.setCostCenterName(costCenterNameMap.get(bizCreateRequest.getCostCenterCode()));

        //如果是一盘货的订单需要先做B信贷校验
        if (OrderCategoryEnum.STOCK.getCode().equals(bizCreateRequest.getOrderCategoryCode())) {
            // B信贷校验
            if (!Boolean.FALSE.equals(bizCreateRequest.getCheckCreditB())) {
                //F-B类型参数去校验B信贷
                SalesOrderBizCreateRequest createRequestTemp = new SalesOrderBizCreateRequest();
                BeanUtils.copyProperties(bizCreateRequest, createRequestTemp);
                //设置F-B特质参数  业务渠道编码 销售组织编码 客户售达方编码
                createRequestTemp.setBusinessChannel(SALES_ORGANIZATION_CODE);
                createRequestTemp.setSalesOrganizationCode(createRequestTemp.getGroupSalesOrganizationCode());
                createRequestTemp.setCustomerCode(createRequestTemp.getGroupCustomerCode());
                if (!isCreditMoneyEnough(createRequestTemp, creditMap)) {
                    return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-042", "SAP信贷额度查询额度不够");
                }
            }

            // 集团收货逻辑仓编码校验
            WarehouseInfo warehouseInfo = cargoZoneAdapter.searchCargoZone(bizCreateRequest.getGroupReceiveWarehouseCode());
            if (Objects.isNull(warehouseInfo)) {
                return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-010", "集团收货仓库不存在");
            }
            Map<String, String> features = Maps.newHashMap();
            features.put("shippingWarehouseCode", warehouseInfo.getCode());
            features.put("shippingWarehouseName", warehouseInfo.getName());
            features.put("deliveryFactoryCode", warehouseInfo.getSapFactoryCode());
            features.put("stockCode", warehouseInfo.getWarehouseCode());
            bizCreateRequest.setFeatures(JSON.toJSONString(features));
        }

        // 信贷校验
        if (!Boolean.FALSE.equals(bizCreateRequest.getCheckCredit())) {
            if (!isCreditMoneyEnough(bizCreateRequest, creditMap)) {
                return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-042", "SAP信贷额度查询额度不够");
            }
        }

        for (SalesOrderAtomCreateLineRequest orderDetail : bizCreateRequest.getOrderDetails()) {
            if (StringUtils.isBlank(orderDetail.getUnitPrice())) {
                // 价格校验放到最后，防止因为送达方、售达方传错报价格错误
                return Result.fail(bizCreateRequest.getSourceOrderNo(), "OC-01-001-01-16-023", "价格格式错误");
            }
        }

        return Result.success(null);
    }

    private Map<String, ItemGroupAbilityDTO> queryScItemGroupMap(List<SalesOrderBizCreateRequest> bizCreateRequests) {
        // 查询所有货品组数据
        ItemGroupAbilityRequest listRequest = new ItemGroupAbilityRequest();
        listRequest.setLimit(999);
        List<ItemGroupAbilityDTO> listResponse = itemQueryAdapter.queryScItemGroup(listRequest);
        return listResponse.stream().collect(Collectors.toMap(ItemGroupAbilityDTO::getProductGroupCode, p -> p, (v1, v2) -> v1));
    }

    /**
     * 信贷余额是否充足
     *
     * @param bizCreateRequest
     * @param creditInfoMap
     * @return
     */
    private boolean isCreditMoneyEnough(SalesOrderBizCreateRequest bizCreateRequest, Map<String, Long> creditInfoMap) {
        Long mainOrderSum = Optional.ofNullable(bizCreateRequest.getOrderDetails()).orElse(Lists.newArrayList()).stream()
                .map(p -> {
                    if (isNumber(p.getActivityTotalAmount())) {
                        return Long.valueOf(p.getActivityTotalAmount());
                    }
                    if (!isNumber(p.getUnitPrice()) || !isNumber(p.getProductQuantity())) {
                        return 0L;
                    }
                    return new BigDecimal(p.getUnitPrice()).multiply(new BigDecimal(p.getProductQuantity())).longValue();
                }).reduce(0L, Long::sum);

        String creditKey = String.format("%s-%s-%s-%s", bizCreateRequest.getSalesOrganizationCode(),
                bizCreateRequest.getCustomerCode(),
                bizCreateRequest.getBusinessChannel(), bizCreateRequest.getProductGroupCode());
        Long balance = creditInfoMap.get(creditKey);
        log.info("信贷校验 bizCreateRequest={},creditInfoMap={} mainOrderSum={}, balance={}", JSON.toJSONString(bizCreateRequest), JSON.toJSONString(creditInfoMap), mainOrderSum, balance);
        if (Objects.isNull(balance)) {
            return false;
        }

        if (balance < mainOrderSum) {
            return false;
        }
        balance = balance - mainOrderSum;
        creditInfoMap.put(creditKey, balance);
        return true;
    }

    private boolean isNumber(String params) {
        if (StringUtils.isBlank(params)) {
            return false;
        }
        String reg = "^\\d+(\\.\\d{1,})$|(^[1-9]\\d*$)";
        return StringUtils.isNumeric(params) || Pattern.compile(reg).matcher(params).matches();
    }

    private Map<String, ShipToPartyByAccurateQueryDTO> queryShipToPartyByAccurate(List<SalesOrderBizCreateRequest> bizCreateRequests, Map<String, ItemGroupAbilityDTO> scItemGroupListQueryMap) {
        List<ShipToPartyByAccurateQueryRequest> requests = Lists.newArrayList();

        for (SalesOrderBizCreateRequest createRequest : bizCreateRequests) {
            if (!scItemGroupListQueryMap.containsKey(createRequest.getProductGroupCode())) {
                // 产品组不存在时，不组装入参查询送达方信息，防止接口报错所有数据都无法拿到
                continue;
            }

            ShipToPartyByAccurateQueryRequest queryRequest = new ShipToPartyByAccurateQueryRequest();
            queryRequest.setBusinessType(createRequest.getProductGroupCode());
            queryRequest.setSalesOrganizationCode(createRequest.getSalesOrganizationCode());
            queryRequest.setShipToPartyCode(createRequest.getShipToPartyCode());
            queryRequest.setSoldToPartyCode(createRequest.getCustomerCode());
            queryRequest.setSalesChannelCode(createRequest.getBusinessChannel());
            if (StringUtils.isNotBlank(createRequest.getGroupShipToPartyCode())) {
                ShipToPartyByAccurateQueryRequest groupQueryRequest = new ShipToPartyByAccurateQueryRequest();
                groupQueryRequest.setBusinessType(createRequest.getProductGroupCode());
                groupQueryRequest.setSalesOrganizationCode(createRequest.getGroupSalesOrganizationCode());
                groupQueryRequest.setShipToPartyCode(createRequest.getGroupShipToPartyCode());
                groupQueryRequest.setSoldToPartyCode(createRequest.getGroupCustomerCode());
                groupQueryRequest.setSalesChannelCode(SALES_ORGANIZATION_CODE);
                requests.add(groupQueryRequest);
            }
            requests.add(queryRequest);
        }
        if (CollectionUtils.isEmpty(requests)) {
            return Maps.newHashMap();
        }
        List<ShipToPartyByAccurateQueryDTO> listResult = shipToPartyAbilityAdapter.queryShipToPartyByAccurate(requests);
        if (CollectionUtils.isEmpty(listResult)) {
            return Maps.newHashMap();
        }

        return listResult.stream().collect(Collectors.toMap(ShipToPartyByAccurateQueryDTO::getShipToPartyCode, p -> p, (v1, v2) -> v1));
    }


    private Map<String, SoldToPartyByAccurateQueryDTO> querySoldToPartyByAccurate(List<SalesOrderBizCreateRequest> bizCreateRequests, Map<String, ItemGroupAbilityDTO> scItemGroupListQueryMap) {
        List<SoldToPartyByAccurateQueryRequest> requests = Lists.newArrayList();

        for (SalesOrderBizCreateRequest createRequest : bizCreateRequests) {
            if (!scItemGroupListQueryMap.containsKey(createRequest.getProductGroupCode())) {
                // 产品组不存在时，不组装入参查询售达方信息，防止接口报错所有数据都无法拿到
                continue;
            }

            SoldToPartyByAccurateQueryRequest queryRequest = new SoldToPartyByAccurateQueryRequest();
            queryRequest.setBusinessType(createRequest.getProductGroupCode());
            queryRequest.setSalesOrganizationCode(createRequest.getSalesOrganizationCode());
            queryRequest.setSoldToPartyCode(createRequest.getCustomerCode());
            queryRequest.setSalesChannelCode(createRequest.getBusinessChannel());
            //如果存在集团售达方，也需要查询
            if (StringUtils.isNotBlank(createRequest.getGroupCustomerCode())) {
                SoldToPartyByAccurateQueryRequest groupQueryRequest = new SoldToPartyByAccurateQueryRequest();
                groupQueryRequest.setBusinessType(createRequest.getProductGroupCode());
                groupQueryRequest.setSalesOrganizationCode(createRequest.getGroupSalesOrganizationCode());
                groupQueryRequest.setSoldToPartyCode(createRequest.getGroupCustomerCode());
                groupQueryRequest.setSalesChannelCode(SALES_ORGANIZATION_CODE);
                requests.add(groupQueryRequest);
            }
            requests.add(queryRequest);
        }

        if (CollectionUtils.isEmpty(requests)) {
            return Maps.newHashMap();
        }

        List<SoldToPartyByAccurateQueryDTO> listResult = soldToPartyAbilityAdapter.querySoldToPartyByAccurate(requests);

        if (CollectionUtils.isEmpty(listResult)) {
            return Maps.newHashMap();
        }

        return listResult.stream().collect(
                Collectors.toMap(SoldToPartyByAccurateQueryDTO::getSoldToPartyCode, p -> p, (v1, v2) -> v1));
    }

    private Map<String, DictionaryResponse> queryBusinessUnit() {
        Map<String, DictionaryResponse> businessUnitMap = new HashMap<>();
        List<DictionaryResponse> businessUnitList = baseDataServiceAdapter.queryDictionarys(DictionaryTypeEnum.BUSINESS_UNIT_CODE.getCode());
        if (CollectionUtils.isNotEmpty(businessUnitList)) {
            businessUnitMap = businessUnitList.stream().collect(Collectors.toMap(DictionaryResponse::getCode, Function.identity(), (x1, x2) -> x2));
        }
        return businessUnitMap;
    }

    private Map<String, String> querySalesOrgByCodeListV2(List<SalesOrderBizCreateRequest> bizCreateRequests) {
        List<String> codeList = bizCreateRequests.stream()
                .map(OrderAtomCreateRequest::getSalesOrganizationCode)
                .filter(StringUtils::isNotBlank).distinct()
                .collect(Collectors.toList());
        return customerCenterAdapter.querySalesOrganization(codeList);
    }

    private Map<String, String> querySalesDeptByCodeList(List<SalesOrderBizCreateRequest> bizCreateRequests) {
        List<String> codeList = bizCreateRequests.stream()
                .map(OrderAtomCreateRequest::getSalesDepartmentCode)
                .filter(StringUtils::isNotBlank).distinct()
                .collect(Collectors.toList());
        return customerCenterAdapter.querySalesDepartment(codeList);
    }

    private Map<String, String> querySalesChannelByCodeList(List<SalesOrderBizCreateRequest> bizCreateRequests) {
        List<String> codeList = bizCreateRequests.stream()
                .map(OrderAtomCreateRequest::getSalesChannelCode)
                .filter(StringUtils::isNotBlank).distinct()
                .collect(Collectors.toList());
        return customerCenterAdapter.querySalesChannel(codeList);
    }

    private Map<String, BusinessChannelDTO> queryBizChannelByCodeList(List<SalesOrderBizCreateRequest> bizCreateRequests) {

        List<String> bizChannelCodeList = bizCreateRequests.stream()
                .map(OrderAtomCreateRequest::getBusinessChannel)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());

        List<BusinessChannelDTO> businessUnitDTOS = businessChannelAbilityAdapter.queryBusinessChannel(bizChannelCodeList);

        if (CollectionUtils.isEmpty(businessUnitDTOS)) {
            return Maps.newHashMap();
        }

        return businessUnitDTOS.stream().collect(Collectors.toMap(BusinessChannelDTO::getChannelCode, p -> p, (v1, v2) -> v1));
    }

    private Map<String, Long> batchQueryCreditList(List<SalesOrderBizCreateRequest> bizCreateRequests) {

        List<CreditQueryRequest> companyCreditQueryRequestList = new ArrayList<>();
        List<QueryCreditRequest> groupCreditQueryRequestList = new ArrayList<>();
        for (SalesOrderBizCreateRequest createRequest : bizCreateRequests) {

            // 集团订单信贷查询
            if (OrderCategoryEnum.GROUP.getCode().equals(createRequest.getOrderCategoryCode())) {
                if (Objects.isNull(createRequest.getCheckCredit()) || createRequest.getCheckCredit()) {
                    QueryCreditRequest groupCreditQueryRequest = new QueryCreditRequest();
                    groupCreditQueryRequest.setSalesOrganizationCode(createRequest.getSalesOrganizationCode());
                    groupCreditQueryRequest.setDistributionChannelCode(createRequest.getBusinessChannel());
                    groupCreditQueryRequest.setBusinessType(createRequest.getProductGroupCode());
                    groupCreditQueryRequest.setSoldToPartyCode(createRequest.getCustomerCode());
                    groupCreditQueryRequestList.add(groupCreditQueryRequest);
                    continue;
                }
            }

            // 一盘货订单信贷查询
            if (OrderCategoryEnum.STOCK.getCode().equals(createRequest.getOrderCategoryCode())) {
                if (Objects.isNull(createRequest.getCheckCreditB()) || createRequest.getCheckCreditB()) {
                    // 集团信贷查询
                    QueryCreditRequest groupCreditQueryRequest = new QueryCreditRequest();
                    groupCreditQueryRequest.setSalesOrganizationCode(createRequest.getGroupSalesOrganizationCode());
                    groupCreditQueryRequest.setDistributionChannelCode(SALES_ORGANIZATION_CODE);
                    groupCreditQueryRequest.setBusinessType(createRequest.getProductGroupCode());
                    groupCreditQueryRequest.setSoldToPartyCode(createRequest.getGroupCustomerCode());
                    groupCreditQueryRequestList.add(groupCreditQueryRequest);
                }
                if (Objects.isNull(createRequest.getCheckCredit()) || createRequest.getCheckCredit()) {
                    // 分子公司信贷查询
                    CreditQueryRequest companyCreditQueryRequest = new CreditQueryRequest();
                    companyCreditQueryRequest.setCustomerCode(createRequest.getCustomerCode());
                    companyCreditQueryRequest.setChannelCode(createRequest.getBusinessChannel());
                    companyCreditQueryRequest.setOrganizationCode(createRequest.getSalesOrganizationCode());
                    companyCreditQueryRequest.setItemGroupCode(createRequest.getProductGroupCode());
                    companyCreditQueryRequestList.add(companyCreditQueryRequest);
                }
                continue;
            }

            // 分子公司订单信贷查询
            if (Objects.isNull(createRequest.getCheckCredit()) || createRequest.getCheckCredit()) {
                CreditQueryRequest companyCreditQueryRequest = new CreditQueryRequest();
                companyCreditQueryRequest.setCustomerCode(createRequest.getCustomerCode());
                companyCreditQueryRequest.setChannelCode(createRequest.getBusinessChannel());
                companyCreditQueryRequest.setOrganizationCode(createRequest.getSalesOrganizationCode());
                companyCreditQueryRequest.setItemGroupCode(createRequest.getProductGroupCode());
                companyCreditQueryRequestList.add(companyCreditQueryRequest);
            }

        }

        Map<String, Long> creditMap = Maps.newHashMap();
        try {
            log.info("companyCreditQueryRequestList={},groupCreditQueryRequestList={}", JSON.toJSONString(companyCreditQueryRequestList), JSON.toJSONString(groupCreditQueryRequestList));
            creditMap.putAll(batchQueryCompanyCreditList(companyCreditQueryRequestList));
            creditMap.putAll(batchQueryGroupCreditList(groupCreditQueryRequestList));
        } catch (Exception e) {
            log.error("SalesOrderCreateBizAssembleOfCustomerCenter#batchQueryCreditList error", e);
        }
        return creditMap;
    }

    /**
     * 查询分子公司信贷
     */
    private Map<String, Long> batchQueryCompanyCreditList(List<CreditQueryRequest> creditQueryRequestList) {
        if (CollectionUtils.isEmpty(creditQueryRequestList)) {
            return Maps.newHashMap();
        }

        //去重同条件信贷查询
        List<CreditQueryRequest> distinctList = creditQueryRequestList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() ->
                                new TreeSet<>(Comparator.comparing(o -> o.getCustomerCode() + "-"
                                        + o.getChannelCode() + "-"
                                        + o.getOrganizationCode() + "-"
                                        + o.getItemGroupCode()))
                        ), ArrayList::new));
        BatchQueryCreditListRequest request = new BatchQueryCreditListRequest();
        request.setRequestList(distinctList);
        log.info("SalesOrderCreateBizAssembleOfCustomerCenter#batchQueryCompanyCreditList request: {}", JSON.toJSONString(request));
        Result<List<CreditInfoSDO>> result = creditQueryService.batchQueryCreditList(request);
        log.info("SalesOrderCreateBizAssembleOfCustomerCenter#batchQueryCompanyCreditList result: {}", JSON.toJSONString(result));
        if (Objects.isNull(result) || CollectionUtils.isEmpty(result.getResult())) {
            return Maps.newHashMap();
        }

        Map<String, Long> creditMap = Maps.newHashMap();
        for (CreditInfoSDO creditInfoSDO : result.getResult()) {
            if (Objects.isNull(creditInfoSDO.getBalance())) {
                continue;
            }
            String creditKey = String.format("%s-%s-%s-%s",
                    creditInfoSDO.getOrganizationCode(),
                    creditInfoSDO.getCustomerCode(),
                    creditInfoSDO.getChannelCode(),
                    creditInfoSDO.getItemGroupCode());
            long balance = new BigDecimal(creditInfoSDO.getBalance()).multiply(new BigDecimal(100)).longValue();
            creditMap.put(creditKey, balance);
        }
        return creditMap;
    }

    /**
     * 查询集团信贷
     */
    private Map<String, Long> batchQueryGroupCreditList(List<QueryCreditRequest> creditQueryRequestList) {
        if (CollectionUtils.isEmpty(creditQueryRequestList)) {
            return Maps.newHashMap();
        }

        //去重同条件信贷查询
        List<QueryCreditRequest> distinctList = creditQueryRequestList.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(() ->
                        new TreeSet<>(Comparator.comparing(o ->
                                String.format("%s-%s-%s-%s",
                                        o.getSalesOrganizationCode(),
                                        o.getSoldToPartyCode(),
                                        o.getDistributionChannelCode(),
                                        o.getBusinessType())))), ArrayList::new));

        QueryGroupCreditRequest request = new QueryGroupCreditRequest();
        request.setData(distinctList);
        log.info("SalesOrderCreateBizAssembleOfCustomerCenter#batchQueryGroupCreditList request: {}", JSON.toJSONString(request));
        Result<QueryCreditResponse> result = mnOrderCenterService.queryGroupCredit(request);
        log.info("SalesOrderCreateBizAssembleOfCustomerCenter#batchQueryGroupCreditList result: {}", JSON.toJSONString(result));
        if (Objects.isNull(result) || Objects.isNull(result.getResult()) || CollectionUtils.isEmpty(result.getResult().getData())) {
            return Maps.newHashMap();
        }

        Map<String, Long> creditMap = Maps.newHashMap();
        for (SapCreditSDO sapCreditSDO : result.getResult().getData()) {
            if (Objects.isNull(sapCreditSDO.getOBLIG())) {
                continue;
            }
            try {
                String creditKey = String.format("%s-%s-%s-%s",
                        sapCreditSDO.getVKORG(), // 销售组织
                        sapCreditSDO.getKUNNR(), // 客户售达方
                        sapCreditSDO.getVTWEG(), // 分销渠道
                        sapCreditSDO.getSPART()); // 产品组
                long balance = new BigDecimal(sapCreditSDO.getDMBTR().replaceAll(" ", ""))
                        .multiply(new BigDecimal(100)).longValue();
                creditMap.put(creditKey, balance);
            } catch (Exception e) {
                log.error("SalesOrderCreateBizAssembleOfCustomerCenter#batchQueryGroupCreditList error", e);
            }
        }
        return creditMap;
    }

    private Map<String, String> queryCostCenterByCodeList(List<SalesOrderBizCreateRequest> bizCreateRequests) {
        List<String> costCenterCodeList = bizCreateRequests.stream()
                .map(OrderAtomCreateRequest::getCostCenterCode)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toList());

        List<CostCenterDTO> costCenterDTOS = customerCenterAdapter.queryCostCenter(costCenterCodeList);

        if (CollectionUtils.isEmpty(costCenterDTOS)) {
            return Maps.newHashMap();
        }

        return costCenterDTOS.stream().collect(Collectors.toMap(CostCenterDTO::getCostCenterCode, CostCenterDTO::getCostCenterName));
    }
}
